package com.easepal.softaplib.wifi;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import com.easepal.softaplib.log.LogUtil;

import java.util.List;

/**
 * 作者: bright.lin@medisana.net.cn
 * 时间: 2018/12/19
 * 标题: WiFi管理器
 * 描述: 管理WiFi各项功能接口
 * 修改: 由 bright.lin@medisana.net.cn 修改于 2018/12/19
 */
@SuppressWarnings("unused")
public class WiFiManager extends BaseWiFiManager {
    private static final String TAG = WiFiManager.class.getName();

    // WiFi管理器对象
    private volatile static WiFiManager mWiFiManager;

    // 网络状态广播接收器
    private NetworkBroadcastReceiver networkBroadcastReceiver;
    // 消息Handler
    private static CallBackHandler mCallBackHandler = new CallBackHandler();
    // WiFi可用监听回调
    private static OnWifiEnabledListener mOnWifiEnabledListener;
    // WiFi扫描结果监听回调
    private static OnWifiScanResultsListener mOnWifiScanResultsListener;
    // WiFi连接监听回调
    private static OnWifiConnectListener mOnWifiConnectListener;

    // WiFi状态-可用
    private static final int WIFI_STATE_ENABLED = 0;
    // WiFi状态-不可用
    private static final int WIFI_STATE_DISABLED = 1;
    // WiFi状态-扫描结果更新
    private static final int SCAN_RESULTS_UPDATED = 2;
    // WiFi状态-连接成功
    private static final int WIFI_CONNECT_SUCCESS = 3;
    // WiFi状态-连接失败
    private static final int WIFI_CONNECT_FAILURE = 4;

    /**
     * 带参构造器
     *
     * @param context 上下文
     */
    private WiFiManager(Context context) {
        super(context);
    }

    /**
     * 获取单例对象
     *
     * @param context 上下文
     * @return 单例对象
     */
    public static WiFiManager getInstance(Context context) {
        if (null == mWiFiManager) {
            synchronized (WiFiManager.class) {
                if (null == mWiFiManager) {
                    mWiFiManager = new WiFiManager(context);
                }
            }
        }
        return mWiFiManager;
    }

    /**
     * 打开Wifi
     */
    public void openWiFi() {
        if (!isWifiEnabled() && null != mWifiManager) {
            mWifiManager.setWifiEnabled(true);
        }
    }

    /**
     * 关闭Wifi
     */
    public void closeWiFi() {
        if (isWifiEnabled() && null != mWifiManager) {
            mWifiManager.setWifiEnabled(false);
        }
    }

    /**
     * 连接到开放网络
     *
     * @param ssid 热点名
     * @return 配置是否成功
     */
    public boolean connectOpenNetwork(@NonNull String ssid) {
        // 获取networkId
        int networkId = setOpenNetwork(ssid);
        if (-1 != networkId) {
            // 保存配置
            boolean isSave = saveConfiguration();
            // 连接网络
            boolean isEnable = enableNetwork(networkId, mOnWifiConnectListener);

            return isSave && isEnable;
        }
        return false;
    }

    /**
     * 连接到WEP网络
     *
     * @param ssid     热点名
     * @param password 密码
     * @return 配置是否成功
     */
    public boolean connectWEPNetwork(@NonNull String ssid, @NonNull String password) {
        // 获取networkId
        int networkId = setWEPNetwork(ssid, password);
        if (-1 != networkId) {
            // 保存配置
            boolean isSave = saveConfiguration();
            // 连接网络
            boolean isEnable = enableNetwork(networkId, mOnWifiConnectListener);

            return isSave && isEnable;
        }
        return false;
    }

    /**
     * 连接到WPA2网络
     *
     * @param ssid     热点名
     * @param password 密码
     * @return 配置是否成功
     */
    public boolean connectWPA2Network(@NonNull String ssid, @NonNull String password) {
        // 获取networkId
        int networkId = setWPA2Network(ssid, password);
        if (-1 != networkId) {
            // 保存配置
            boolean isSave = saveConfiguration();
            // 连接网络
            boolean isEnable = enableNetwork(networkId, mOnWifiConnectListener);

            return isSave && isEnable;
        }
        return false;
    }

    /**
     * 广播接收者
     */
    public static class NetworkBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            if (null == intent || null == intent.getAction() || null == wifiManager) return;
            switch (intent.getAction()) {
                case WifiManager.WIFI_STATE_CHANGED_ACTION: // WIFI状态发生变化
                    switch (intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN)) {
                        case WifiManager.WIFI_STATE_ENABLING:
                            LogUtil.i(TAG, "onReceive: 正在打开 WIFI...");
                            break;
                        case WifiManager.WIFI_STATE_ENABLED:
                            LogUtil.i(TAG, "onReceive: WIFI 已打开");
                            mCallBackHandler.sendEmptyMessage(WIFI_STATE_ENABLED);
                            break;
                        case WifiManager.WIFI_STATE_DISABLING:
                            LogUtil.i(TAG, "onReceive: 正在关闭 WIFI...");
                            break;
                        case WifiManager.WIFI_STATE_DISABLED:
                            LogUtil.i(TAG, "onReceive: WIFI 已关闭");
                            mCallBackHandler.sendEmptyMessage(WIFI_STATE_DISABLED);
                            break;
                        case WifiManager.WIFI_STATE_UNKNOWN:
                        default:
                            LogUtil.i(TAG, "onReceive: WIFI 状态未知!");
                            break;
                    }
                    break;
                case WifiManager.SCAN_RESULTS_AVAILABLE_ACTION: // WIFI扫描完成
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                        boolean isUpdated = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false);
                        LogUtil.i(TAG, "onReceive: WIFI扫描  " + (isUpdated ? "完成" : "未完成"));
                    } else {
                        LogUtil.i(TAG, "onReceive: WIFI扫描完成");
                    }

                    Message scanResultsMessage = Message.obtain();
                    scanResultsMessage.what = SCAN_RESULTS_UPDATED;
                    scanResultsMessage.obj = wifiManager.getScanResults();
                    mCallBackHandler.sendMessage(scanResultsMessage);
                    break;
                case WifiManager.NETWORK_STATE_CHANGED_ACTION: // WIFI连接状态发生改变
//                    LogUtil.i(TAG, "onReceive: WIFI连接状态发生改变");
//                    NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
//                    if (null != networkInfo && ConnectivityManager.TYPE_WIFI == networkInfo.getType()) {
//                    }
//                    WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO);
                    WifiInfo wifiInfo = mWiFiManager.getConnectionInfo();
                    if (null != wifiInfo && wifiInfo.getSupplicantState() == SupplicantState.COMPLETED) {
                        String ssid = wifiInfo.getSSID();
                        LogUtil.i(TAG, "onReceive: 网络连接成功 ssid = " + ssid);
                        Message wifiConnectSuccessMessage = Message.obtain();
                        wifiConnectSuccessMessage.what = WIFI_CONNECT_SUCCESS;
                        wifiConnectSuccessMessage.obj = ssid;
                        mCallBackHandler.sendMessage(wifiConnectSuccessMessage);
                    }
                    break;
                case WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION:
                    boolean isConnected = intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false);
                    LogUtil.i(TAG, "onReceive: SUPPLICANT_CONNECTION_CHANGE_ACTION  isConnected = " + isConnected);
                    break;
                case WifiManager.SUPPLICANT_STATE_CHANGED_ACTION: // WIFI连接请求状态发生改变
                    // 获取连接状态
                    SupplicantState supplicantState = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);

                    switch (supplicantState) {
                        case INTERFACE_DISABLED: // 接口禁用
                            LogUtil.i(TAG, "onReceive: INTERFACE_DISABLED 接口禁用");
                            break;
                        case INACTIVE: // 不活跃的
                            WifiInfo connectFailureInfo = wifiManager.getConnectionInfo();
                            LogUtil.i(TAG, "onReceive: INACTIVE 不活跃的  connectFailureInfo = " + connectFailureInfo);
                            break;
                        case SCANNING: // 正在扫描
                            LogUtil.i(TAG, "onReceive: SCANNING 正在扫描");
                            break;
                        case AUTHENTICATING: // 正在验证
                            LogUtil.i(TAG, "onReceive: AUTHENTICATING: // 正在验证");
                            break;
                        case ASSOCIATING: // 正在关联
                            LogUtil.i(TAG, "onReceive: ASSOCIATING: // 正在关联");
                            break;
                        case ASSOCIATED: // 已经关联
                            LogUtil.i(TAG, "onReceive: ASSOCIATED: // 已经关联");
                            break;
                        case FOUR_WAY_HANDSHAKE:
                            LogUtil.i(TAG, "onReceive: FOUR_WAY_HANDSHAKE:");
                            break;
                        case GROUP_HANDSHAKE:
                            LogUtil.i(TAG, "onReceive: GROUP_HANDSHAKE:");
                            break;
                        case COMPLETED: // 完成
                            LogUtil.i(TAG, "onReceive: WIFI_CONNECT_SUCCESS: // 完成");
                            WifiInfo connectSuccessInfo = wifiManager.getConnectionInfo();
//                            if (null != connectSuccessInfo) {
//                                Message wifiConnectSuccessMessage = Message.obtain();
//                                wifiConnectSuccessMessage.what = WIFI_CONNECT_SUCCESS;
//                                wifiConnectSuccessMessage.obj = connectSuccessInfo.getSSID();
//                                mCallBackHandler.sendMessage(wifiConnectSuccessMessage);
//                            }
                            break;
                        case DORMANT:
                            LogUtil.i(TAG, "onReceive: DORMANT:");
                            break;
                        case UNINITIALIZED: // 未初始化
                            LogUtil.i(TAG, "onReceive: UNINITIALIZED: // 未初始化");
                            break;
                        case INVALID: // 无效的
                            LogUtil.i(TAG, "onReceive: INVALID: // 无效的");
                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 注册网络状态广播接收
     *
     * @param context 上下文
     */
    public void registerBroadcastReceivers(Context context) {
        if (networkBroadcastReceiver == null) {
            networkBroadcastReceiver = new NetworkBroadcastReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("android.net.wifi.SCAN_RESULTS");
            intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
            intentFilter.addAction("android.net.wifi.STATE_CHANGE");
            intentFilter.addAction("android.net.wifi.supplicant.STATE_CHANGE");
            intentFilter.addAction("android.net.wifi.supplicant.CONNECTION_CHANGE");
            context.getApplicationContext().registerReceiver(networkBroadcastReceiver, intentFilter);
        }
    }

    /**
     * 注销网络状态广播接收
     *
     * @param context 上下文
     */
    private void unregisterBroadcastReceivers(Context context) {
        if (null != networkBroadcastReceiver) {
            context.getApplicationContext().unregisterReceiver(networkBroadcastReceiver);
            networkBroadcastReceiver = null;
        }
    }

    /**
     * 释放资源
     *
     * @param context 上下文
     */
    public void onDestory(Context context) {
        unregisterBroadcastReceivers(context);
        removeOnWifiConnectListener();
        removeOnWifiEnabledListener();
        removeOnWifiScanResultsListener();
    }

    /**
     * 消息Handler实现
     */
    private static class CallBackHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WIFI_STATE_ENABLED: // WIFI已经打开
                    if (null != mOnWifiEnabledListener) {
                        mOnWifiEnabledListener.onWifiEnabled(true);
                    }
                    break;
                case WIFI_STATE_DISABLED: // WIFI已经关闭
                    if (null != mOnWifiEnabledListener) {
                        mOnWifiEnabledListener.onWifiEnabled(false);
                    }
                    break;
                case SCAN_RESULTS_UPDATED: // WIFI扫描完成
                    if (null != mOnWifiScanResultsListener) {
                        @SuppressWarnings("unchecked")
                        List<ScanResult> scanResults = (List<ScanResult>) msg.obj;
                        mOnWifiScanResultsListener.onScanResults(excludeRepetition(scanResults));
                    }
                    break;
                case WIFI_CONNECT_SUCCESS: // WIFI连接完成
                    if (null != mOnWifiConnectListener) {
                        String ssid = (String) msg.obj;
                        mOnWifiConnectListener.onWiFiConnectSuccess(ssid);
                    }
                    break;
                case WIFI_CONNECT_FAILURE: // WIFI连接完成
                    if (null != mOnWifiConnectListener) {
                        String ssid = (String) msg.obj;
                        mOnWifiConnectListener.onWiFiConnectFailure(ssid);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /*注册、注销监听回调**/
    public void setOnWifiEnabledListener(OnWifiEnabledListener listener) {
        mOnWifiEnabledListener = listener;
    }

    private void removeOnWifiEnabledListener() {
        mOnWifiEnabledListener = null;
    }

    public void setOnWifiScanResultsListener(OnWifiScanResultsListener listener) {
        mOnWifiScanResultsListener = listener;
    }

    private void removeOnWifiScanResultsListener() {
        mOnWifiScanResultsListener = null;
    }

    public void setOnWifiConnectListener(OnWifiConnectListener listener) {
        mOnWifiConnectListener = listener;
    }

    private void removeOnWifiConnectListener() {
        mOnWifiConnectListener = null;
    }
    /*注册、注销监听回调**/
}
